<template>
  <el-tabs v-model="currentTab.name" class="demo-tabs" closable @tab-click="handleClick" @tab-remove="remove">
    <el-tab-pane 
            v-for="item in tabs"
            :key="item.name"
            :label="item.name"
            :name="item.name"
        >
            <template #label>
                <span class="custom-tabs-label">
                    <el-icon>
                        <component :is="item.icon" />
                    </el-icon>
                    <span>{{ item.name }}</span>
                </span>
            </template>
            <!-- route的内容 -->
        </el-tab-pane>
  </el-tabs>
  <router-view></router-view>

</template>

<script setup>
import { useTabsStore } from "@/stores/modules/tabs";
import { storeToRefs } from "pinia";
import { useRouter,useRoute } from 'vue-router';
const route=useRoute()
import router from "@/router";
import { ref } from "vue";

let routers = useRouter()
let useTabs = useTabsStore();
let { tabs,currentTab } = storeToRefs(useTabs);
let {setCurrentTab} = useTabs
let menus = ref([]);
menus.value = router.options.routes.filter((route) => route.path == "/admin")[0].children;
const {addTab,removeTab}=useTabs;
// addTab(name,url,icon)
// console.log("useTabs",useTabs);

const handleClick = ({index}) => { 
    routers.push(tabs.value[index].path) //路由跳转
    setCurrentTab(tabs.value[index].name,tabs.value[index].path) //设置当前
}

function findObjectByUrl(arr, url) {
  for (const item of arr) {
    if (item.path === url) {
      return item;
    }
    if (item.children) {
      const found = findObjectByUrl(item.children, url);
      if (found) {
        return found;
      }
    }
  }
  return null; // 如果未找到，返回 null
}

const {name,path,icon}=findObjectByUrl(menus.value,route.path)

addTab(name,path,icon)
setCurrentTab(name,path)

const remove = (TabPaneName) => {
  
    removeTab(TabPaneName);
    console.log();
    
    routers.push(currentTab.value.path)
}
</script>

<style lang="scss" scoped>
 .demo-tabs {
  ::v-deep  .is-active{color: white !important;background-color: #38b781;border-radius: 15px;}
  ::v-deep .custom-tabs-label>.el-icon{
    margin-left: 10px;
  }
  ::v-deep .el-tabs__item>.el-icon{
    margin-right: 10px;
  }
  ::v-deep .el-tabs__active-bar{
    background-color: transparent;
  }
  ::v-deep .el-tabs__item{
    padding: 0;
  }
  }
</style>
